package com.rtwo.tio.server.handler;

import com.rtwo.tio.common.*;
import com.rtwo.tio.client.msg.LoginRequest;
import com.rtwo.tio.server.msg.LoginResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.json.Json;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * Created by hasee on 2018/7/5.
 */
public class LoginResponseHandler extends BasicHandler<LoginRequest>{

    @Override
    public Class<LoginRequest> getClazz() {
        return LoginRequest.class;
    }

    @Override
    public void postHanlder(LoginRequest body, ChannelContext channelContext) throws UnsupportedEncodingException {
        LoginResponse loginResponse = new LoginResponse();
        if("123456".equals(body.getPassword())){
            loginResponse.setCode(LoginResponse.SUCCESS);
            loginResponse.setToken(UUID.randomUUID().toString());
            loginResponse.setMsg("登录成功");
            Tio.bindUser(channelContext,body.getUsername());
            channelContext.setAttribute("username",body.getUsername());
        }else{
            loginResponse.setCode(LoginResponse.FAIL);
            loginResponse.setMsg("登录失败");
            loginResponse.setToken(null);
        }
        Tio.send(channelContext,new BasicPacket(MsgType.LOGIN_RESP, Json.toJson(loginResponse).getBytes(Common.CHARSET)));
    }
}
